<template>
  <div class="compare-container">
    <!-- 顶部导航栏 -->
    <div class="compare-header">
      <div class="header-content">
        <el-button
          icon="el-icon-arrow-left"
          class="back-btn"
          @click="goBack">
          返回
        </el-button>
        <h1 class="compare-title">商品对比分析</h1>
        <div class="spacer"></div>
      </div>
    </div>

    <!-- 商品对比区域 -->
    <div class="compare-content">
      <div class="products-comparison">
        <h2 class="section-title">
          <i class="el-icon-s-grid"></i>
          商品信息对比
        </h2>
        <div class="products-grid">
          <div
            v-for="item in compareItems"
            :key="item.id"
            class="product-card">
            <img
              :src="item.image || defaultImage"
              class="product-image"
              alt="商品图片">
            <div class="product-info">
              <h3 class="product-name">{{ item.title }}</h3>
              <p class="product-desc">{{ item.sellPoint }}</p>
              <div class="product-price">¥{{ item.price }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- AI分析结果区域 -->
      <div class="ai-analysis">
        <div class="analysis-header">
          <h2 class="section-title">
            <i class="el-icon-cpu"></i>
            AI 智能分析
          </h2>
          <el-button
            type="primary"
            :loading="analyzing"
            :disabled="analyzing || analysisResult !== ''"
            @click="startAiAnalysis"
            class="analyze-btn">
            {{ analyzing ? '分析中...' : '开始AI分析' }}
          </el-button>
        </div>

        <!-- 分析结果 -->
        <div v-if="analyzing" class="loading-container">
          <div class="loading-animation">
            <i class="el-icon-loading"></i>
          </div>
          <p class="loading-text">AI正在为您分析商品，请稍候...</p>
        </div>

        <div v-else-if="analysisResult" class="analysis-result">
          <div class="result-content" v-html="formatAnalysisResult(analysisResult)"></div>
        </div>

        <div v-else class="empty-analysis">
          <i class="el-icon-chat-dot-round empty-icon"></i>
          <p class="empty-text">点击"开始AI分析"按钮，让AI帮你分析这些商品</p>
        </div>

        <!-- 错误提示 -->
        <div v-if="errorMessage" class="error-message">
          <i class="el-icon-warning"></i>
          {{ errorMessage }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "CompareView",
  data() {
    return {
      compareItems: [],
      analyzing: false,
      analysisResult: '',
      errorMessage: '',
      defaultImage: "https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png"
    };
  },
  created() {
    // 从路由参数获取商品数据
    const items = this.$route.params.items || [];
    if (items.length < 2) {
      this.$message.warning('商品数据不足，至少需要2个商品');
      this.$router.push('/shop');
      return;
    }
    this.compareItems = items;
    document.title = "商品对比分析";
  },
  methods: {
    goBack() {
      this.$router.go(-1);
    },

    async startAiAnalysis() {
      this.analyzing = true;
      this.errorMessage = '';
      this.analysisResult = '';

      try {
        // 准备商品数据
        const productsInfo = this.compareItems.map((item, index) => ({
          序号: index + 1,
          商品名称: item.title,
          卖点: item.sellPoint,
          价格: item.price
        }));

        console.log('📤 发送AI分析请求...');

        // 使用axios直接调用，设置更长的超时时间（60秒）
        const axios = require('axios');
        const response = await axios.post('/api/ai/compare', {
          products: productsInfo
        }, {
          timeout: 60000,  // 60秒超时
          headers: {
            'Content-Type': 'application/json'
          }
        });

        console.log('📥 收到响应:', response.data);

        if (response.data.code === '0') {
          this.analysisResult = response.data.data.analysis;
          this.$message.success('✅ AI分析完成！');
          console.log('✅ AI分析成功，结果长度:', this.analysisResult.length);
        } else {
          this.errorMessage = response.data.msg || 'AI分析失败，请稍后重试';
          this.$message.error(this.errorMessage);
        }
      } catch (error) {
        console.error('❌ AI分析错误:', error);
        this.errorMessage = '网络错误或AI服务暂时不可用';

        // 如果是超时错误，提示用户
        if (error.code === 'ECONNABORTED') {
          this.errorMessage = '请求超时，请检查网络连接或稍后重试';
          this.$message.error('请求超时，AI服务响应较慢，请稍后重试');
        } else if (error.response) {
          // 服务器返回了错误
          this.errorMessage = `服务器错误: ${error.response.status}`;
          this.$message.error(this.errorMessage);
        } else {
          this.$message.error('网络错误，请检查连接');
        }
      } finally {
        this.analyzing = false;
      }
    },

    getMockAnalysis() {
      const items = this.compareItems;
      return `
### 📊 商品对比分析报告

#### 一、基本信息对比

${items.map((item, index) => `
**商品${index + 1}：${item.title}**
- 💰 价格：¥${item.price}
- 📝 卖点：${item.sellPoint}
`).join('\n')}

#### 二、价格分析

${this.analyzePrices()}

#### 三、性价比分析

${this.analyzeCostPerformance()}

#### 四、购买建议

${this.getBuyingSuggestion()}

---
*本分析由AI智能生成，仅供参考*
      `;
    },

    analyzePrices() {
      const prices = this.compareItems.map(item => item.price);
      const maxPrice = Math.max(...prices);
      const minPrice = Math.min(...prices);
      const avgPrice = (prices.reduce((a, b) => a + b, 0) / prices.length).toFixed(2);

      const maxIndex = prices.indexOf(maxPrice);
      const minIndex = prices.indexOf(minPrice);

      return `
- 📈 价格区间：¥${minPrice} - ¥${maxPrice}
- 📊 平均价格：¥${avgPrice}
- 💎 最高价：商品${maxIndex + 1}（¥${maxPrice}）
- 💰 最低价：商品${minIndex + 1}（¥${minPrice}）
- 📉 价差：¥${(maxPrice - minPrice).toFixed(2)}
      `;
    },

    analyzeCostPerformance() {
      const items = this.compareItems;
      return items.map((item, index) => {
        const priceLevel = item.price > 1000 ? '高端' : item.price > 500 ? '中端' : '入门';
        return `
**商品${index + 1}分析：**
- 定位：${priceLevel}产品
- 特点：${item.sellPoint.substring(0, 50)}...
- 适合人群：${this.getSuitableGroup(item.price)}
        `;
      }).join('\n');
    },

    getSuitableGroup(price) {
      if (price > 2000) return '追求品质、预算充足的用户';
      if (price > 1000) return '注重性价比、有一定预算的用户';
      if (price > 500) return '预算适中、追求实用的用户';
      return '预算有限、追求经济实惠的用户';
    },

    getBuyingSuggestion() {
      const prices = this.compareItems.map(item => item.price);
      const minPrice = Math.min(...prices);
      const minIndex = prices.indexOf(minPrice);
      const maxPrice = Math.max(...prices);
      const maxIndex = prices.indexOf(maxPrice);

      return `
1. **预算优先选择：** 如果注重性价比，推荐选择商品${minIndex + 1}（¥${minPrice}），价格最实惠。

2. **品质优先选择：** 如果追求品质和体验，可以考虑商品${maxIndex + 1}（¥${maxPrice}），通常高价位产品在品质和功能上更有优势。

3. **综合建议：** 建议根据个人实际需求和预算综合考虑。查看商品详细信息、用户评价，选择最适合自己的产品。

4. **购买时机：** 建议关注商家活动和优惠券，可以获得更优惠的价格。
      `;
    },

    formatAnalysisResult(result) {
      // 将Markdown格式转换为HTML，支持更丰富的格式
      let html = result;

      // 处理分隔线
      html = html.replace(/^---+$/gm, '<hr class="divider">');

      // 处理标题
      html = html.replace(/^# (.*?)$/gm, '<h1 class="analysis-h1">$1</h1>');
      html = html.replace(/^## (.*?)$/gm, '<h2 class="analysis-h2">$1</h2>');
      html = html.replace(/^### (.*?)$/gm, '<h3 class="analysis-h3">$1</h3>');
      html = html.replace(/^#### (.*?)$/gm, '<h4 class="analysis-h4">$1</h4>');

      // 处理表格（简单表格格式：| 列1 | 列2 | 列3 |）
      const tableRegex = /(\|[^\n]+\|\n)+/g;
      html = html.replace(tableRegex, (match) => {
        const lines = match.trim().split('\n');
        if (lines.length === 0) return match;

        let tableHtml = '<div class="analysis-table-wrapper"><table class="analysis-table">';

        lines.forEach((line, index) => {
          // 跳过分隔线（|-----|-----|）
          if (line.match(/^\|[-:\s|]+\|$/)) return;

          const cells = line.split('|').filter(cell => cell.trim() !== '');
          const tag = index === 0 ? 'th' : 'td';

          tableHtml += '<tr>';
          cells.forEach(cell => {
            const content = cell.trim();
            // 为包含价格的单元格添加特殊样式
            const priceClass = content.match(/¥\d+/) ? ' class="price-cell"' : '';
            tableHtml += `<${tag}${priceClass}>${content}</${tag}>`;
          });
          tableHtml += '</tr>';
        });

        tableHtml += '</table></div>';
        return tableHtml;
      });

      // 处理粗体文本
      html = html.replace(/\*\*(.*?)\*\*/g, '<strong class="highlight">$1</strong>');
      html = html.replace(/【(.*?)】/g, '<span class="badge">$1</span>');

      // 处理列表项（包括中文列表标记）
      html = html.replace(/^[|｜]\s*(.*?)\s*[|｜]\s*(.*?)\s*$/gm, '<div class="info-row"><span class="info-label">$1</span><span class="info-value">$2</span></div>');
      html = html.replace(/^[-•]\s+(.*?)$/gm, '<li class="analysis-li">$1</li>');

      // 处理备注和提示信息
      html = html.replace(/^>\s*(备注|注意|提示)[:：]\s*(.*?)$/gm, '<div class="note-box"><i class="el-icon-warning-outline"></i><span>$1：$2</span></div>');

      // 将连续的<li>标签包装在<ul>中
      html = html.replace(/(<li class="analysis-li">.*?<\/li>\s*)+/gs, (match) => {
        return `<ul class="analysis-ul">${match}</ul>`;
      });

      // 处理段落
      html = html.split('\n\n').map(paragraph => {
        paragraph = paragraph.trim();
        if (!paragraph) return '';
        // 如果已经是HTML标签，直接返回
        if (paragraph.match(/^<[^>]+>/)) return paragraph;
        // 否则包装为段落
        return `<p class="analysis-p">${paragraph}</p>`;
      }).join('\n');

      // 处理换行
      html = html.replace(/\n/g, '<br>');

      // 添加emoji图标优化
      html = html.replace(/价格/g, '<i class="el-icon-sell icon-inline"></i>价格');
      html = html.replace(/性价比/g, '<i class="el-icon-star-on icon-inline"></i>性价比');
      html = html.replace(/品牌/g, '<i class="el-icon-medal icon-inline"></i>品牌');

      return `<div class="markdown-content">${html}</div>`;
    }
  }
}
</script>

<style scoped>
.compare-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
}

.compare-header {
  background: white;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px 30px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.back-btn {
  flex-shrink: 0;
}

.compare-title {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
}

.spacer {
  flex: 1;
}

.compare-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 20px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 20px 0;
}

.section-title i {
  color: #ff6b35;
  font-size: 24px;
}

/* 商品对比区域 */
.products-comparison {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 30px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.product-card {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.product-card:hover {
  border-color: #ff6b35;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-4px);
}

.product-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  background: white;
  border-radius: 8px;
  margin-bottom: 15px;
}

.product-info {
  text-align: left;
}

.product-name {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-desc {
  font-size: 13px;
  color: #6c757d;
  line-height: 1.5;
  margin: 0 0 15px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.product-price {
  font-size: 24px;
  font-weight: 700;
  color: #ff6b35;
}

/* AI分析区域 */
.ai-analysis {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.analysis-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.analyze-btn {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  border: none;
  padding: 12px 30px;
  font-weight: 600;
}

.loading-container {
  text-align: center;
  padding: 60px 20px;
}

.loading-animation {
  font-size: 48px;
  color: #ff6b35;
  margin-bottom: 20px;
}

.loading-animation i {
  animation: rotating 1s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 16px;
  color: #6c757d;
}

.analysis-result {
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  padding: 30px;
  line-height: 1.8;
}

.result-content {
  color: #2c3e50;
}

/* 标题样式 */
.result-content >>> .analysis-h1 {
  font-size: 28px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 25px 0;
  padding: 20px;
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  color: white;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 4px 12px rgba(255, 107, 53, 0.3);
}

.result-content >>> .analysis-h2 {
  font-size: 22px;
  font-weight: 700;
  color: #2c3e50;
  margin: 30px 0 20px 0;
  padding: 15px 20px;
  background: linear-gradient(90deg, #ff6b35 0%, transparent 100%);
  border-left: 5px solid #ff6b35;
  border-radius: 4px;
  background: #fff3e0;
}

.result-content >>> .analysis-h2:first-child {
  margin-top: 0;
}

.result-content >>> .analysis-h3 {
  font-size: 18px;
  font-weight: 600;
  color: #495057;
  margin: 25px 0 15px 0;
  padding-left: 15px;
  border-left: 3px solid #ff6b35;
}

.result-content >>> .analysis-h4 {
  font-size: 16px;
  font-weight: 600;
  color: #6c757d;
  margin: 20px 0 10px 0;
}

/* 分隔线 */
.result-content >>> .divider {
  border: none;
  height: 2px;
  background: linear-gradient(90deg, transparent, #ff6b35, transparent);
  margin: 30px 0;
}

/* 表格样式 */
.result-content >>> .analysis-table-wrapper {
  overflow-x: auto;
  margin: 20px 0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.result-content >>> .analysis-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  font-size: 14px;
}

.result-content >>> .analysis-table th {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  color: white;
  padding: 12px 16px;
  text-align: left;
  font-weight: 600;
  border: none;
}

.result-content >>> .analysis-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #e9ecef;
  color: #495057;
}

.result-content >>> .analysis-table tr:last-child td {
  border-bottom: none;
}

.result-content >>> .analysis-table tr:hover {
  background: #f8f9fa;
}

.result-content >>> .analysis-table .price-cell {
  color: #ff6b35;
  font-weight: 600;
  font-size: 16px;
}

/* 信息行样式（键值对） */
.result-content >>> .info-row {
  display: flex;
  padding: 12px 16px;
  margin: 8px 0;
  background: white;
  border-radius: 6px;
  border-left: 3px solid #ff6b35;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.result-content >>> .info-row:hover {
  transform: translateX(5px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.result-content >>> .info-label {
  font-weight: 600;
  color: #ff6b35;
  min-width: 120px;
  flex-shrink: 0;
}

.result-content >>> .info-value {
  color: #495057;
  flex: 1;
}

/* 粗体和徽章 */
.result-content >>> .highlight {
  color: #ff6b35;
  font-weight: 600;
  padding: 2px 4px;
  background: rgba(255, 107, 53, 0.1);
  border-radius: 3px;
}

.result-content >>> .badge {
  display: inline-block;
  padding: 4px 12px;
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  color: white;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  margin: 0 4px;
}

/* 列表样式 */
.result-content >>> .analysis-ul {
  list-style: none;
  padding: 0;
  margin: 15px 0;
}

.result-content >>> .analysis-li {
  padding: 10px 15px 10px 40px;
  margin: 8px 0;
  position: relative;
  background: white;
  border-radius: 6px;
  border-left: 3px solid #dee2e6;
  transition: all 0.3s ease;
}

.result-content >>> .analysis-li:hover {
  border-left-color: #ff6b35;
  background: #fff8f5;
  transform: translateX(5px);
}

.result-content >>> .analysis-li:before {
  content: '●';
  position: absolute;
  left: 15px;
  color: #ff6b35;
  font-weight: bold;
  font-size: 18px;
}

/* 段落样式 */
.result-content >>> .analysis-p {
  margin: 12px 0;
  color: #495057;
  line-height: 1.8;
}

/* 备注框 */
.result-content >>> .note-box {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 20px;
  margin: 20px 0;
  background: #fff8e1;
  border-left: 4px solid #ffc107;
  border-radius: 6px;
  color: #856404;
  box-shadow: 0 2px 8px rgba(255, 193, 7, 0.2);
}

.result-content >>> .note-box i {
  font-size: 24px;
  color: #ffc107;
}

/* 内联图标 */
.result-content >>> .icon-inline {
  color: #ff6b35;
  margin-right: 4px;
  font-size: 16px;
}

.empty-analysis {
  text-align: center;
  padding: 80px 20px;
}

.empty-icon {
  font-size: 64px;
  color: #dee2e6;
  margin-bottom: 20px;
}

.empty-text {
  font-size: 16px;
  color: #6c757d;
}

.error-message {
  background: #fee;
  border: 1px solid #fcc;
  border-radius: 8px;
  padding: 15px;
  color: #c33;
  margin-top: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.error-message i {
  font-size: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .compare-content {
    padding: 20px 15px;
  }

  .products-grid {
    grid-template-columns: 1fr;
  }

  .analysis-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .analyze-btn {
    width: 100%;
  }
}
</style>

